import config, { getApiUrl } from './config'
import { getCurrentToken, clearLoginData } from './auth'

// 声明uni类型
declare const uni: any

// 审批流程状态工具函数
export const workflowUtils = {
	// 获取步骤状态样式
	getStepStatusClass: (status: string): string => {
		const statusMap: Record<string, string> = {
			'pending': 'pending',
			'approved': 'approved',
			'rejected': 'rejected',
			'canceled': 'canceled'
		}
		return statusMap[status] || 'pending'
	},

	// 获取步骤状态文本
	getStepStatusText: (status: string): string => {
		const statusMap: Record<string, string> = {
			'pending': '待审批',
			'approved': '已通过',
			'rejected': '已拒绝',
			'canceled': '已取消'
		}
		return statusMap[status] || '待审批'
	},

	// 获取流程类型文本
	getWorkflowTypeText: (type: string): string => {
		const typeMap: Record<string, string> = {
			'leave': '请假申请',
			'purchase': '采购申请',
			'payment': '付款申请',
			'missedPunch': '补卡申请',
			'businessTrip': '出差申请',
			'expense': '报销申请',
			'seal': '用章申请',
			'vehicle': '用车申请'
		}
		return typeMap[type] || '未知类型'
	}
}

// 统一的API请求方法
const request = (options: any) => {
	return new Promise<{ success: boolean, data?: any, total?: number, message?: string }>((resolve, reject) => {
		// 获取当前用户token
		const token = getCurrentToken()

		// 合并请求头，添加Token
		const headers = {
			...config.headers,
			...options.header
		}

		// 如果有token，添加到请求头
		if (token) {
			headers.Token = token
		} else {
			console.log('API请求未添加Token（用户未登录）')
		}

		const requestOptions = {
			method: 'GET',
			header: headers,
			timeout: config.timeout,
			...options,
			url: getApiUrl(options.url)
		}

		uni.request({
			...requestOptions,
			success: (res: any) => {
				if (res.statusCode === 200) {
					// console.log('API请求成功:', res.data)
					if (res.data.code == '200') {
						resolve({
							success: true,
							...res.data
						})
					}
					else if (res.data.code == '401') {
						// Token无效或过期，清除登录数据
						console.log('Token无效，清除登录数据')
						// clearLoginData()

						// #ifdef H5
						// H5环境下刷新页面以显示登录框
						uni.showToast({
							title: '登录已过期，请重新登录',
							icon: 'none',
							duration: 2000
						})
						setTimeout(() => {
							window.location.reload()
						}, 2000)
						// #endif

						// // #ifndef H5
						// // 非H5环境下跳转到首页
						// uni.reLaunch({
						// 	url: '/pages/home/home'
						// })
						// // #endif
						resolve({ success: false, message: '登录已过期，请重新登录' })

					}
					else {
						resolve({ success: false, message: res.data.msg })
					}
				} else if (res.statusCode === 401) {
					// Token无效或过期，清除登录数据
					console.log('Token无效，清除登录数据')
					//clearLoginData()

					// #ifdef H5
					// H5环境下刷新页面以显示登录框
					uni.showToast({
						title: '登录已过期，请重新登录',
						icon: 'none',
						duration: 2000
					})
					setTimeout(() => {
						window.location.reload()
					}, 2000)
					// #endif

					// #ifndef H5
					// 非H5环境下跳转到首页
					uni.reLaunch({
						url: '/pages/home/home'
					})
					// #endif

					reject({
						type: 'AUTH_ERROR',
						statusCode: res.statusCode,
						message: '登录已过期，请重新登录',
						data: res.data
					})
				} else {
					reject({
						type: 'HTTP_ERROR',
						statusCode: res.statusCode,
						message: `请求失败: ${res.statusCode}`,
						data: res.data
					})
				}
			},
			fail: (error: any) => {
				console.error('API请求失败:', error)
				reject({
					type: 'NETWORK_ERROR',
					message: '网络错误，请稍后重试',
					error
				})
			}
		})
	})
}

// 请假相关API
export const leaveApi = {
	// 提交请假申请
	apply: (data: any) => {
		return request({
			url: config.api.leave.apply,
			method: 'POST',
			data
		})
	},

	// 获取请假列表
	getList: (params: any) => {
		return request({
			url: config.api.leave.list,
			method: 'GET',
			data: params
		})
	},

	// 获取请假详情
	getDetail: (id: string) => {
		return request({
			url: `${config.api.leave.detail}/${id}`,
			method: 'GET'
		})
	},

	// 取消请假申请
	cancel: (id: string) => {
		return request({
			url: config.api.leave.cancel,
			method: 'POST',
			data: { id }
		})
	},

	// 获取审批人列表
	getApprovers: (projectId: string, workflowType: string) => {
		return request({
			url: config.api.approvers,
			method: 'GET',
			data: {
				project_id: projectId,
				workflow_type: workflowType,
				page: 1,
			}
		})
	}
}

// 采购相关API
export const purchaseApi = {
	// 提交采购申请
	apply: (data: any) => {
		return request({
			url: config.api.purchase.apply,
			method: 'POST',
			data
		})
	},

	// 获取采购列表
	getList: (params: any) => {
		return request({
			url: config.api.purchase.list,
			method: 'GET',
			data: params
		})
	},

	// 获取采购详情
	getDetail: (id: string) => {
		return request({
			url: `${config.api.purchase.detail}/${id}`,
			method: 'GET'
		})
	},

	// 取消采购申请
	cancel: (id: string) => {
		return request({
			url: config.api.purchase.cancel,
			method: 'POST',
			data: { id }
		})
	},

	// 获取审批人列表
	getApprovers: (projectId: string, workflowType: string) => {
		return request({
			url: config.api.approvers,
			method: 'GET',
			data: {
				project_id: projectId,
				workflow_type: workflowType,
				page: 1,
			}
		})
	},
}


export const paymentApi = {
	apply: (data: any) => {
		return request({
			url: config.api.payment.apply,
			method: 'POST',
			data
		})
	},

	getApprovers: (projectId: string, workflowType: string) => {
		return request({
			url: config.api.approvers,
			method: 'GET',
			data: {
				project_id: projectId,
				workflow_type: workflowType,
				page: 1,
			}
		})
	},

	getDetail: (id: string) => {
		return request({
			url: `${config.api.payment.detail}/${id}`,
			method: 'GET'
		})
	},

	getList: (params: any) => {
		return request({
			url: config.api.payment.list,
			method: 'GET',
			data: params
		})
	},

	cancel: (id: string) => {
		return request({
			url: config.api.payment.cancel,
			method: 'POST',
			data: { id }
		})
	},

}


export const userApi = {
	login: (data: any) => {
		return request({
			url: config.api.user.login,
			method: 'POST',
			data
		})
	},
	getUserInfo: () => {
		return request({
			url: config.api.user.info,
			method: 'GET',
		})
	},
	wxAuth: (data: any) => {
		return request({
			url: config.api.user.wxAuth || '/wx-auth',
			method: 'POST',
			data
		})
	},
	updateAvatar: (avatarUrl: string) => {
		return request({
			url: config.api.user.updateAvatar,
			method: 'POST',
			data: { avatarUrl }
		})
	}
}

// 工作流相关API
export const workflowApi = {
	// 获取我的申请列表
	getMyApplications: (params = {}) => {
		return request({
			url: config.api.workflow.myApplications,
			method: 'GET',
			data: params
		})
	},

	getWorkflowInstance: (id: string) => {
		return request({
			url: config.api.workflow.instance(id),
			method: 'GET'
		})
	},

	// 获取待我审批的任务
	getPendingApprovals: (params: any) => {
		return request({
			url: config.api.workflow.pendingApprovals,
			method: 'GET',
			data: params
		})
	},

	// 审批流程
	approve: (instance_id: string,  remark: string) => {
		return request({
			url: config.api.workflow.approveAction,
			method: 'POST',
			data: {
				action: "approve",
				instance_id: instance_id,
				remark: remark
			}
		})
	},

	// 拒绝流程
	reject: (instance_id: string, remark: string) => {
		return request({
			url: config.api.workflow.approveAction,
			method: 'POST',
			data: {
				action: "reject",
				instance_id: instance_id,
				remark: remark
			}
		})
	},

	// 提交入库单
	submitInventory: (data: any) => {
		return request({
			url: config.api.workflow.inventory,
			method: 'POST',
			data
		})
	},

	// 获取入库记录
	getInventoryRecord: (workflowId: string) => {
		return request({
			url: config.api.workflow.inventoryRecord(workflowId),
			method: 'GET'
		})
	}
}

// 考勤打卡相关API
export const attendanceApi = {
	// 获取今日打卡状态
	getTodayStatus: () => {
		return request({
			url: config.api.attendance.todayStatus,
			method: 'GET'
		})
	},

	// 打卡（上班/下班）
	clockIn: (data: any) => {
		return request({
			url: config.api.attendance.clockIn,
			method: 'POST',
			data
		})
	},

	// 获取打卡记录列表
	getRecords: (params: any) => {
		return request({
			url: config.api.attendance.records,
			method: 'GET',
			data: params
		})
	},

	// 申请补卡
	applyMissedPunch: (data: any) => {
		return request({
			url: config.api.attendance.missedPunch,
			method: 'POST',
			data
		})
	},

	// 获取审批人列表
	getApprovers: (projectId: string) => {
		return request({
			url: config.api.attendance.approvers,
			method: 'GET',
			data: {
				project_id: projectId,
				workflow_type: 'attendance',
				page: 1,
			}
		})
	}
}

// 项目管理相关API
export const projectApi = {
	// 获取项目列表
	getProjects: () => {
		return request({
			url: config.api.project.list,
			method: 'GET'
		})
	},

	// 获取项目详情
	getProjectDetail: (id: string) => {
		return request({
			url: `${config.api.project.detail}/${id}`,
			method: 'GET'
		})
	},

	// 更新项目位置信息
	updateProjectLocation: (data: any) => {
		return request({
			url: config.api.project.updateLocation,
			method: 'POST',
			data
		})
	},

	getProjectLocation: (ids: string[]) => {
		return request({
			url: `${config.api.project.location}`,
			data: {
				ids: ids.join(',')
			},
			method: 'GET'
		})
	}
}

